package pedrosm.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import pedrosm.utils.Debug;


public class ScriptData<T> extends Data {
	private static ScriptEngine engine = new ScriptEngineManager()
			.getEngineByName("groovy");

	private Class<? extends T> script = null;

	private void debug(Object fvalue) {
		Debug.debug("Script", fvalue);
	}

	@SuppressWarnings("unchecked")
	public ScriptData(String name, String group, String path) {
		setName(name);
		setGroup(group);

		try {
			File file = new File(path);
			if (!file.exists()) {
				debug(path + " could not be found");
				return;
			}

			BufferedReader reader = new BufferedReader(new FileReader(path));
			StringBuilder buffer = new StringBuilder();

			String fline;
			while ((fline = reader.readLine()) != null) {
				if (buffer.length() > 0)
					buffer.append("\n");
				buffer.append(fline);
			}
			reader.close();

			setScript((Class<? extends T>) engine.eval(buffer.toString()));
		} catch (Exception e) {
			debug("Failed to load script (" + name + ")");
		}
	}

	// Instance
	public Object instance() {
		if (getScript() != null) {
			try {
				return getScript().newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	// Get & Set
	public Class<? extends T> getScript() {
		return script;
	}

	public void setScript(Class<? extends T> script) {
		this.script = script;
	}
}